﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;

namespace Utility.DataSystem
{
	/// <summary>
	/// Will auto close if main window is closed
	/// </summary>
	public abstract class AuxSettingObjectEditorWindow : EditorWindow
	{
		IEditorWindow mainWindow;
		Func<bool> validator;

		protected abstract GUIContent TitleContent { get; }

		protected virtual void OnEnable ()
		{
			titleContent = TitleContent;
		}

		public static TWindow OpenWindow<TWindow> (IEditorWindow mainWindow, Func<TWindow, bool> validator = null)
			where TWindow : AuxSettingObjectEditorWindow
		{
			var window = GetWindow<TWindow> ();
			window.mainWindow = mainWindow;
			if (validator != null)
			{
				window.validator = () => validator (window);
			}

			window.Show ();
			return window;
		}

		private void OnGUI ()
		{
			if (mainWindow == null || !mainWindow.IsOpen)
			{
				Close ();
				return;
			}
			if (!(validator?.Invoke () ?? true))
			{
				OnInvalidAction ();
			}

			DrawGUI ();
		}

		protected abstract void DrawGUI ();

		protected virtual void OnInvalidAction ()
		{
			Close ();
		}
	}
}